import { defineStore } from 'pinia';

// 稳定序列化：按 key 排序，确保相同参数生成相同 key
function stableStringify(obj) {
  if (obj === null || typeof obj !== 'object') return String(obj);
  if (Array.isArray(obj))
    return `[${obj.map((v) => stableStringify(v)).join(',')}]`;
  const keys = Object.keys(obj).sort();
  const parts = keys.map(
    (k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`
  );
  return `{${parts.join(',')}}`;
}

export const useCollegeListCache = defineStore('collegeListCache', {
  state: () => ({
    // page 缓存：key -> { list, hasMore, timestamp }
    pages: {},
    // 滚动位置：baseKey -> number
    scrollTopByBaseKey: {},
    // 缓存过期时间（毫秒）
    ttlMs: 10 * 60 * 1000, // 10 分钟
  }),
  actions: {
    makeBaseKey(params) {
      return stableStringify(params);
    },
    makePageKey(baseKey, pageNo) {
      return `${baseKey}::${pageNo}`;
    },
    getPage(pageKey) {
      const entry = this.pages[pageKey];
      if (!entry) return null;
      if (Date.now() - entry.timestamp > this.ttlMs) {
        // 过期自动清理
        delete this.pages[pageKey];
        return null;
      }
      return entry;
    },
    setPage(pageKey, payload) {
      this.pages[pageKey] = {
        list: payload.list || [],
        hasMore: Boolean(payload.hasMore),
        timestamp: Date.now(),
      };
    },
    clearByBaseKeyPrefix(baseKeyPrefix) {
      const keys = Object.keys(this.pages);
      keys.forEach((k) => {
        if (k.startsWith(baseKeyPrefix)) delete this.pages[k];
      });
    },
    setScrollTop(baseKey, top) {
      this.scrollTopByBaseKey[baseKey] = Number(top) || 0;
    },
    getScrollTop(baseKey) {
      return this.scrollTopByBaseKey[baseKey] || 0;
    },
  },
  persist: {
    storage: sessionStorage,
    paths: ['pages', 'scrollTopByBaseKey'],
  },
});
